package com.saibo.spider.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class IpConfigUtils {
	// 获取MAC地址的方法
	public static String getMACAddress() {

		// 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
		byte[] mac = null;
		try {
			InetAddress ia = InetAddress.getLocalHost();// 获取本地IP对象
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (Exception e) {
			System.err.println("GetMacAddress Error");
			return null;
		}

		// 下面代码是把mac地址拼装成String
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			// mac[i] & 0xFF 是为了把byte转化为正整数
			String s = Integer.toHexString(mac[i] & 0xFF);
			sb.append(s.length() == 1 ? 0 + s : s);
		}

		// 把字符串所有小写字母改为大写成为正规的mac地址并返回
		return sb.toString().toUpperCase();
	}

	public static String getNetIPAddress() {
		try {
			String html = HttpResponseUtil.getHtml(HttpRequestUtil.getRequestMethod("http://1212.ip138.com/ic.asp", null), "gb2312");
			String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(html);
			String ip = "";
			while (m.find()) {
				ip = m.group();
			}
			return ip;
		} catch (IllegalStateException e) {
			return "0.0.0.0";
		}
	}
	
	public static String getLocalIp(){
		InetAddress ia=null;
		try {
			ia=InetAddress.getLocalHost();
			//String localname=ia.getHostName();
			String localip=ia.getHostAddress();
			return localip;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args) {
		getLocalIp();
	}

}
